package com.railwayserviceWX.util;

import net.sf.json.JSONObject;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

/**
 * java调用中央气象局天气预报接口
 *
 * @author lid
 * @date 2017.3.11
 */
public class WeatherUtil {
	private static final Logger logger = LoggerFactory.getLogger(WeatherUtil.class);
	/**
	 * 通过新浪的天气预报接口获取天气状况
	 * @param city
	 * @return
	 * @throws IOException
	 * @throws NullPointerException
	 * @throws ParserConfigurationException
	 * @throws SAXException
	 * @author lid
	 */
	public static Map<String, Object> getWeatherFromSina(String city) throws IOException, NullPointerException, ParserConfigurationException, SAXException{
		logger.info("city:"+city);
		String cityGB = URLEncoder.encode(city, "GB2312");
		logger.info("cityGB:"+cityGB);
		if(cityGB.endsWith("%CA%D0")){
			cityGB = cityGB.substring(0, cityGB.length() - "%CA%D0".length());
		}
		logger.info("cityGB:"+cityGB);
		// 连接新浪气象台的API
        URL url = new URL("http://php.weather.sina.com.cn/xml.php?city="+cityGB+"&password=DJOYnieT8234jlsK&day=1");
        URLConnection connectionData = url.openConnection();
        connectionData.setConnectTimeout(1000);
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(connectionData.getInputStream(), "UTF-8"));
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = br.readLine()) != null)
                sb.append(line);
            String datas = sb.toString();
            datas = datas.substring(datas.indexOf("<Profiles>"));
            StringReader sr = new StringReader(datas);
            InputSource is = new InputSource(sr);
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder=factory.newDocumentBuilder(); 
            Document doc = builder.parse(is);

            String cityName = doc.getElementsByTagName("city").item(0).getTextContent();
            String temp1 = doc.getElementsByTagName("temperature1").item(0).getTextContent();
            String temp2 = doc.getElementsByTagName("temperature2").item(0).getTextContent();
            String weather = doc.getElementsByTagName("status1").item(0).getTextContent();
            String ptime = doc.getElementsByTagName("udatetime").item(0).getTextContent();
            map.put("city", cityName);// 城市
            map.put("temp1", temp1);// 最高温度
            map.put("temp2", temp2);// 最低温度
            map.put("weather", weather);//天气
            map.put("ptime", ptime);// 发布时间
        } catch (SocketTimeoutException e) {
            System.out.println("连接超时");
        } catch (FileNotFoundException e) {
            System.out.println("加载文件出错");
        }
        return map;
	}
	
    /**
     * 获取实时天气1<br>
     * 方 法 名： getTodayWeather <br>
     *
     * @param Cityid 城市编码
     */
    public static Map<String, Object> getWeather(String cityid) throws IOException, NullPointerException {
        // 连接中央气象台的API
        URL url = new URL("http://www.weather.com.cn/data/cityinfo/" + cityid
                + ".html");

        URLConnection connectionData = url.openConnection();
        connectionData.setConnectTimeout(1000);
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(connectionData.getInputStream(), "UTF-8"));
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = br.readLine()) != null)
                sb.append(line);
            String datas = sb.toString();
            System.out.println(datas);
            JSONObject jsonData = JSONObject.fromObject(datas);
            JSONObject info = jsonData.getJSONObject("weatherinfo");
            map.put("city", info.getString("city").toString());// 城市
            map.put("temp1", info.getString("temp1").toString());// 最高温度
            map.put("temp2", info.getString("temp2").toString());// 最低温度
            map.put("weather", info.getString("weather").toString());//天气
            map.put("ptime", info.getString("ptime").toString());// 发布时间
        } catch (SocketTimeoutException e) {
            System.out.println("连接超时");
        } catch (FileNotFoundException e) {
            System.out.println("加载文件出错");
        }
        return map;
    }

    public static void main(String[] args) {
        try {
            //测试获取实时天气1(包含风况，湿度)
            /*Map<String, Object> map2 = getWeather("101010100");
            System.out.println(map2.get("city") + "\t" + map2.get("temp1")
                    + "\t" + map2.get("temp2") + "\t" + map2.get("weather")
                    + "\t" + map2.get("ptime"));*/
        	System.out.println(getWeatherFromSina("长沙市").toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
